
package com.ipinyou.util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ipinyou.tools.PyidUtils;
import com.ipy.util.StringUtil;


/**
 * Title. cookie辅助类<br>
 * Description.
 * <p>
 * Copyright: Copyright (c) 2011 5 6 14:56:36
 * <p>
 * Company: 北京品友互动信息技术有限公司
 * <p>
 * Author: wen.lv@ipinyou.com
 * <p>
 * Version: 1.0
 * <p>
 */
public class CookieHelper {
private static final String PYID="PYID";
private static final String JSTYPE="jsType";
/**判断pyid的cookie是否存在
 * @param request
 * @return
 */
private static Cookie getCookiePyId(HttpServletRequest request)
{
	Cookie result=null;
	result=new Cookie(PYID, null);
	Cookie cookies[] = request.getCookies();
	if(cookies!=null)//查客户端是否存在PYID
	{
		for (int i = 0; i < cookies.length; i++)
		 {
			if (cookies[i].getName().trim().equals(PYID)) 
			{
			    result=cookies[i];
			}							
		 }
	  }
	 return result;
	
}

	/**
	 * 客户端pyid存在取出，客户端不存在新建
	 * @param request
	 * @param response
	 * @return
	 */
	public static String pyidCookie(HttpServletRequest request,HttpServletResponse response)
	{
		String result=null;
		result=getCookiePyId(request).getValue();
	
		response.setHeader("P3P","CP=\"NON DSP COR CURa ADMa DEVa TAIa PSAa PSDa IVAa IVDa CONa HISa TELa OTPa OUR UNRa IND UNI COM NAV INT DEM CNT PRE LOC\"");
		 if(StringUtil.isEmpty(result))//客户端不存在，新生成。
		 {
		 //result=DateUtil.getTime(DateUtil.yyyyMMddHHmmssxxx_INT)+get6Random();
		 result=PyidUtils.generate();
			Cookie cookie=null;
			cookie=new Cookie(PYID, result);
			cookie.setMaxAge(24 * 3600 * 365);
			cookie.setPath("/");
			cookie.setDomain(".ipinyou.com");
			response.addCookie(cookie);
			
			
		 }
		String jsType= request.getParameter(JSTYPE);
		if("1".equals(jsType)||"2".equals(jsType)){
			Cookie cookie=null;
			cookie=new Cookie(JSTYPE, request.getParameter(JSTYPE));
			cookie.setMaxAge(24 * 3600 * 365);
			cookie.setPath("/");
			cookie.setDomain(".ipinyou.com");
			response.addCookie(cookie);
		}
			
	
		 return result;
		
	}
	

}
